
package com.hsc.www.rawTest.事务;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

public class 解决办法A {
    public static void main(String[] args) throws Exception {
        //创建ConnectionFactory
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setUsername("guest");
        connectionFactory.setPassword("guest");
        connectionFactory.setHost("127.0.0.1");
        connectionFactory.setVirtualHost("my_vhost");
        connectionFactory.setPort(5672);
        //获取 connection
        Connection connection = connectionFactory.newConnection();
        //通过connection创建一个新的Channel
        Channel channel = connection.createChannel();

        String QUEUE_NAME = "tx_queue";
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);

        try {
            channel.txSelect();
            for (int i = 0; i < 10; i++) {
                channel.basicPublish("", QUEUE_NAME, null, "消息".getBytes());
            }
//            int id = 1 / 0;
            channel.txCommit();
        } catch (Exception e) {
            e.printStackTrace();
            channel.txRollback();
        }
    }
}
